<script setup>
import { useAppStore } from '@/store'

const appStore = useAppStore()
const route = useRoute()

const layouts = new Map()

function getLayout(name) {
  // 利用map将加载过的layout缓存起来，防止重新加载layout导致页面闪烁
  if (layouts.get(name))
    return layouts.get(name)
  const layout = markRaw(
    defineAsyncComponent(() => import(`@/layouts/${name}/index.vue`)),
  )
  layouts.set(name, layout)
  return layout
}

if (!appStore.layout)
  appStore.setLayout('empty')

// 获取展示组件的布局组件
const Layout = computed(() => {
  if (!route.matched?.length)
    return null
  return getLayout(route.meta?.layout || appStore.layout)
})
</script>

<template>
  <router-view v-if="Layout" v-slot="{ Component, route: curRoute }">
    <!-- 布局组件 -->
    <component :is="Layout">
      <!-- 展示的组件 -->
      <component :is="Component" :key="curRoute.fullPath" />
    </component>
  </router-view>
</template>

<style scoped></style>
